<?php

class Admin_Sign_Controller extends Base_Controller {


	public $restful = true;
	public function __construct(){
		$this->_data = array();
		$this->model_users= new Users();
		if (!Auth::check())
		{
			return Redirect::to('admin/sign/in');
		}
		/*$this->filter('before', 'csrf')->on('post');
		echo Form::token();
		echo Session::token();
		
		 */
	}

	public function post_in()
	{
		$this->_data['input'] = Input::get();
		$credentials = array('username' => Input::get('username'), 'password' => Input::get('password'));
 
		$rules = array(
				'captcha' => 'laracaptcha|required'
				);
		$validation = Validator::make(Input::all(), $rules);

		if (!$validation->valid())
		{
			echo Response::json(array("state"=>false,'message'=>'用户验证码错误'));
			return;
		} 


		if (Auth::attempt($credentials))
		{
			Session::put('username',Input::get('username'));
			echo Response::json(array("state"=>true));
			return;
		}

		echo Response::json(array("state"=>false,'message'=>"用户名或者密码错误"));
		//view
	}

	public function get_out()
	{
		Session::forget('username');
		Auth::logout();
		return Redirect::to('/admin/sign/in');

	}

	public function action_addUser()
	{
		
		$this->_data["vp"] = $this->validate_parameter();
		$this->_data["input"] = Input::get();
		if($this->_data["vp"] === True ){
			$input = Input::get();
			unset($input['confirm']);
			$input['password'] = Hash::make($input['password']);
			$this->_data["state"]= $this->model_users->addUsers($input);
		}

		var_dump($this->_data);
		//view
	}



	public function action_updateUsers()
	{
		$id = Input::get('id');
		$update_array = array();
		foreach(array('email','phone') as $key){
			$value = Input::get($key);
			if($value) $update_array[$key] = $value;
		}
		$this->_data["state"] = $this->model_users->updateUsers($id,$update_array);

		var_dump($this->_data);
	}

	private function action_deleteUsers()
	{
		$id = Input::get('id');
		$this->_data["state"] = $this->model_users->deleteUsers($id);
		var_dump($this->_data);
	}

	private function action_listUsers()
	{
		$this->_data["users_list"] = $this->model_users->listUsers();
		var_dump($this->_data);
	}

	public function action_getUsers()
	{
		$id = Input::get('id');
		$this->_data["users"] = $this->model_users->getUsers($id);
		var_dump($this->_data);
	}

	private function validate_parameter(){

		$input = Input::get();
		$rules = array(
			'username'  => 'required|max:50',
			'password' => 'required',
			'confirm' => 'required',
			'email' => '',
			'phone' => '',
			'gender' => ''
		);

		$validation = Validator::make($input, $rules);

		if ($validation->fails())
		{
			return $validation->errors;
		}

		return True;	

	}

}
